package com.lib.common.view.ui;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.FrameLayout;

import java.util.ArrayList;
import java.util.List;

public class GestureLayout extends FrameLayout {
    // 手势类型
    private final int GESTURE_NONE = 0;
    private final int GESTURE_TAP = 1;
    private final int GESTURE_DOUBLE_TAP = 2;
    private final int GESTURE_LONG_PRESS = 3;

    // 常量
    private final int TAP_TIMEOUT = 200;
    private final int DOUBLE_TAP_TIMEOUT = 300;
    private final int LONG_PRESS_TIMEOUT = 500;
    private final int MAX_TAP_DISTANCE = 20;
    private final int TOUCH_SLOP = 10;

    // 手势识别变量
    private int mCurrentGesture = GESTURE_NONE;
    private float mStartX, mStartY;
    private float mLastX, mLastY;
    private long mDownTime;
    private long mFirstTapTime;
    private boolean mIsDoubleTapPossible;
    private boolean mIsLongPressTriggered;
    private Runnable mLongPressRunnable;

    // 触摸轨迹绘制
    private Paint mPathPaint;
    private Paint mCirclePaint;
    private Path mTouchPath;
    private List<PointF> mTouchPoints;
    private boolean mVisualizeTouch = true;

    // 监听器
    private OnGestureListener mOnGestureListener;

    // 手势状态
    public interface OnGestureListener {
        void onTap(float x, float y);

        void onDoubleTap(float x, float y);

        void onLongPress(float x, float y);
    }


    // 公共方法
    public void setOnGestureListener(OnGestureListener listener) {
        mOnGestureListener = listener;
    }

    public GestureLayout(Context context) {
        this(context, null);
    }

    public GestureLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public GestureLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        setWillNotDraw(false); // 允许绘制

        // 初始化画笔
        mPathPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPathPaint.setColor(Color.RED);
        mPathPaint.setStrokeWidth(dpToPx(1));
        mPathPaint.setStyle(Paint.Style.STROKE);

        mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mCirclePaint.setColor(Color.BLUE);
        mCirclePaint.setStyle(Paint.Style.FILL);

        mTouchPath = new Path();
        mTouchPoints = new ArrayList<>();

        mLongPressRunnable = new Runnable() {
            @Override
            public void run() {
                if (!mIsLongPressTriggered) {
                    mIsLongPressTriggered = true;
                    mCurrentGesture = GESTURE_LONG_PRESS;

                    if (mOnGestureListener != null) {
                        mOnGestureListener.onLongPress(mLastX, mLastY);
                    }
                    invalidate();
                }
            }
        };
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return false; // 拦截所有触摸事件
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();

        switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                handleActionDown(x, y);
                break;

            case MotionEvent.ACTION_MOVE:
                handleActionMove(x, y);
                break;

            case MotionEvent.ACTION_UP:
                handleActionUp(x, y);
                break;

            case MotionEvent.ACTION_CANCEL:
                handleActionCancel();
                break;
        }

        // 记录触摸轨迹
        if (mVisualizeTouch) {
            recordTouchPoint(x, y, event.getActionMasked());
        }

        invalidate(); // 触发重绘
        return true;
    }

    private void handleActionDown(float x, float y) {
        mStartX = x;
        mStartY = y;
        mLastX = x;
        mLastY = y;
        mDownTime = System.currentTimeMillis();
        mIsLongPressTriggered = false;

        // 检查双击
        long currentTime = System.currentTimeMillis();
        if (currentTime - mFirstTapTime < DOUBLE_TAP_TIMEOUT &&
                distance(x, y, mLastX, mLastY) < MAX_TAP_DISTANCE) {
            mIsDoubleTapPossible = true;
        }

        // 开始长按检测
        postDelayed(mLongPressRunnable, LONG_PRESS_TIMEOUT);

        mCurrentGesture = GESTURE_NONE;
    }

    private void handleActionMove(float x, float y) {
        float deltaX = x - mLastX;
        float deltaY = y - mLastY;
        mLastX = x;
        mLastY = y;

        // 检查是否达到滑动阈值
        if (mCurrentGesture == GESTURE_NONE) {
            float distance = distance(x, y, mStartX, mStartY);
            if (distance > TOUCH_SLOP) {
                removeCallbacks(mLongPressRunnable);
            }
        }
    }

    private void handleActionUp(float x, float y) {
        removeCallbacks(mLongPressRunnable);
        long currentTime = System.currentTimeMillis();

        switch (mCurrentGesture) {
            case GESTURE_NONE:
                // 点击或双击
                if (currentTime - mDownTime < TAP_TIMEOUT &&
                        distance(x, y, mStartX, mStartY) < MAX_TAP_DISTANCE) {

                    if (mIsDoubleTapPossible) {
                        // 双击
                        mCurrentGesture = GESTURE_DOUBLE_TAP;
                        if (mOnGestureListener != null) {
                            mOnGestureListener.onDoubleTap(x, y);
                        }
                        mIsDoubleTapPossible = false;
                    } else {
                        // 单击
                        mCurrentGesture = GESTURE_TAP;
                        if (mOnGestureListener != null) {
                            mOnGestureListener.onTap(x, y);
                        }
                        mFirstTapTime = currentTime;
                        mIsDoubleTapPossible = true;
                    }
                }
                break;
        }

        // 重置状态
        mCurrentGesture = GESTURE_NONE;
        clearTouchPoints();
    }

    private void handleActionCancel() {
        removeCallbacks(mLongPressRunnable);
        mCurrentGesture = GESTURE_NONE;
        clearTouchPoints();
    }

    private void recordTouchPoint(float x, float y, int action) {
        if (action == MotionEvent.ACTION_DOWN) {
            mTouchPath.reset();
            mTouchPoints.clear();
            mTouchPath.moveTo(x, y);
        } else if (action == MotionEvent.ACTION_MOVE) {
            mTouchPath.lineTo(x, y);
        }
        mTouchPoints.add(new PointF(x, y));
    }

    private void clearTouchPoints() {
        if (!mVisualizeTouch) {
            mTouchPath.reset();
            mTouchPoints.clear();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (mVisualizeTouch && !mTouchPoints.isEmpty()) {
            // 绘制触摸路径
            canvas.drawPath(mTouchPath, mPathPaint);

            // 绘制当前触摸点圆圈
            PointF lastPoint = mTouchPoints.get(mTouchPoints.size() - 1);
            canvas.drawCircle(lastPoint.x, lastPoint.y, dpToPx(15), mCirclePaint);
        }
    }

    public void setVisualizeTouch(boolean visualize) {
        mVisualizeTouch = visualize;
        if (!visualize) {
            clearTouchPoints();
        }
        invalidate();
    }

    // 工具方法
    private float distance(float x1, float y1, float x2, float y2) {
        float dx = x1 - x2;
        float dy = y1 - y2;
        return (float) Math.sqrt(dx * dx + dy * dy);
    }

    private float dpToPx(float dp) {
        return dp * getResources().getDisplayMetrics().density;
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        removeCallbacks(mLongPressRunnable);
    }
}